const axios = require('axios')
const trash = require('@/utils/ini.unit')
const accessToken = {
  expires: new Date().getTime(),
  token: null
}

function getAccessToken () {
  return new Promise((resolve, reject) => {
    if (accessToken.expires <= new Date().getTime()) {
      axios({
        method: 'get',
        url: 'https://api.weixin.qq.com/cgi-bin/token',
        params: {
          grant_type: 'client_credential',
          appid: trash.appid,
          secret: trash.secret
        }
      })
        .then(response => {
          if (response.data.errcode) {
            reject(response.data)
          } else {
            resolve(response.data.access_token)
            Object.assign(accessToken, {
              token: response.data.access_token,
              expires: new Date().getTime() + response.data.expires_in * 1000
            })
          }
        })
        .catch(err => {
          reject(err)
        })
    } else {
      resolve(accessToken.token)
    }
  })
}

module.exports = getAccessToken
